package com.hxzy.commons.util;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * JSON工具类
 */
@SuppressWarnings("serial")
public class JSONLibUtil implements java.io.Serializable
{

	public static String serializeObjectToJSON(Object obj)
	{
		if (obj == null)
			return null;
		else
		{
			JSONObject jsonObject = JSONObject
					.fromObject(obj);
			return jsonObject.toString();
		}
	}

	@SuppressWarnings("unchecked")
	public static Object deserializeJSONToObject(
			String json, Class rootClass,
			Map classMapping)
	{
		JSONObject jsonObject = JSONObject.fromObject(json);
		if (classMapping != null)
			return JSONObject.toBean(
					jsonObject,
					rootClass,
					classMapping);
		else
			return JSONObject.toBean(jsonObject, rootClass);
	}

	@SuppressWarnings("unchecked")
	public static Map deserializeJSONToMap(String json) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		Iterator<?> it = jsonObject.keys();
		Map map = null;
		while (it.hasNext()) {
			Object key = it.next();
			Object o = jsonObject.get(key);
			if(map == null )map = new HashMap();
			map.put(key, o);
		}
		return map;
	}
	
	/**
	 * 解析Json数组到Collection
	 * @param json
	 * @return
	 */
	public static Collection<?> deserializeJSONArrayToMap(String json){
		JSONArray jsonArray = JSONArray.fromObject(json);
		Collection<?> collection = JSONArray.toCollection(jsonArray);
		if(null != collection && !collection.isEmpty()){
			return collection;
		}
		return null;
	}
	
	/**
	 * 将map对象转换成json字符串
	 * @param map
	 * @return
	 */
	public static String Map2Json(Map map){
		JSONObject json = JSONObject.fromObject(map);
		return json.toString();
	}
	
	public static void main(String[] args) {
		Map map = new HashMap<String,String>();
		map.put("id", "1");
		map.put("pid", "0");
		map.put("name", "节点");
		System.out.println(Map2Json(map));
	}
}
